/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package za.co.pas.business.model;

import za.co.pas.business.abstracts.AbstractDataModel;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import za.co.pas.business.data.Company;
import za.co.pas.business.message.CompanyListChanged;
import za.co.pas.business.message.StatusMessage;
import za.co.pas.business.message.StatusMessageObject;

/**
 *
 * @author alabuschagne
 */
public class CompanyDataModel extends AbstractDataModel
{
    private static Logger logger = Logger.getLogger(CompanyDataModel.class);
    private List<Company> companies = new LinkedList<Company>();
    public void loadAllCompanies(boolean force)
    {
        List<Company> cmps = getCompanies(force);
        firePropertyChange(new CompanyListChanged(companies));
    }
    /**
     *
     * @param force force a fetch from db
     * @return
     */
    public List<Company> getCompanies(boolean force)
    {
        if((companies == null) || (companies.isEmpty()) || (force))
        {
            companies = getCompaniesFromDB();
            Collections.sort((List)companies);
        }
        return companies;
    }

    private List<Company> getCompaniesFromDB()
    {
        try
        {
            firePropertyChange(new StatusMessage(StatusMessageObject.SMO_INFO, "Getting all companies", StatusMessageObject.SMO_TYPE_READ));
            Query q = em.createQuery("SELECT c FROM Company c");
            setConnectionOk(true);
            return (List<Company>) q.getResultList();
        }
        catch (NoResultException ex)
        {
            //This is not a error
            firePropertyChange(new StatusMessage(StatusMessageObject.SMO_WARN, "No results for companies", StatusMessageObject.SMO_TYPE_READ));
            logger.info(ex.getMessage());
        }
        catch (NonUniqueResultException ex)
        {
            firePropertyChange(new StatusMessage(StatusMessageObject.SMO_ERROR, "Reading error: " + ex.getMessage(), StatusMessageObject.SMO_TYPE_READ));
            logger.error(ex.getMessage(), ex);
        }
        catch (IllegalStateException ex)
        {
            firePropertyChange(new StatusMessage(StatusMessageObject.SMO_ERROR, "Reading error: " + ex.getMessage(), StatusMessageObject.SMO_TYPE_READ));
            logger.error(ex.getMessage(), ex);
        }
        catch (IllegalArgumentException ex)
        {
            firePropertyChange(new StatusMessage(StatusMessageObject.SMO_ERROR, "Reading error: " + ex.getMessage(), StatusMessageObject.SMO_TYPE_READ));
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    public String makeCompanyCode(String s)
    {
        int count = 0;
        String str = s;
        str = str.substring(0,3).toUpperCase();
        //count how many starts with this
        if(companies == null)
        {
            companies = getCompanies(true);
        }

        if(companies != null)
        {
            ListIterator<Company> it = companies.listIterator();
            while(it.hasNext())
            {
                Company co = it.next();
                if(co.getName().toUpperCase().startsWith(str))
                {
                    count++;
                }
            }
        }
        count++;
        String sCount = Integer.toString(count);
        for(int i = sCount.length(); i < 4; i++)
        {
            str += "0";
        }
        str += sCount;
        return str;
    }
}
